from flask import Blueprint, request, jsonify
from config.config import FILE_UPLOAD_PATH, ALLOWED_EXTENSIONS
import os

upload_bp = Blueprint('upload', __name__)


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@upload_bp.route('/upload', methods=['POST'])
def upload_file():
    """
    支持三种上传方式：
        1. multipart/form-data （标准表单）
        2. application/octet-stream （原始二进制流）
        3. JSON Base64 编码
    """

    content_type = request.headers.get('Content-Type', '')

    file_data = None
    original_filename = None

    # 方法一：multipart/form-data
    if 'multipart/form-data' in content_type:
        if 'file' not in request.files:
            return jsonify({"error": "No file part"}), 400
        file = request.files['file']
        if file.filename == '':
            return jsonify({"error": "No selected file"}), 400
        if not allowed_file(file.filename):
            return jsonify({
                "error": f"File type not allowed. Allowed: {', '.join(ALLOWED_EXTENSIONS)}"
            }), 400
        file_data = file.stream.read()
        original_filename = file.filename

    # 方法二：application/octet-stream（二进制流）
    elif 'application/octet-stream' in content_type:
        original_filename = request.args.get('filename') or request.headers.get('X-File-Name')
        if not original_filename:
            return jsonify({"error": "Missing filename parameter or header"}), 400
        if not allowed_file(original_filename):
            return jsonify({
                "error": f"File type not allowed. Allowed: {', '.join(ALLOWED_EXTENSIONS)}"
            }), 400
        file_data = request.data

    # 方法三：application/json + base64
    elif 'application/json' in content_type:
        json_data = request.get_json(silent=True)
        if not json_data or 'file_base64' not in json_data or 'filename' not in json_data:
            return jsonify({"error": "Invalid JSON format"}), 400

        original_filename = json_data['filename']
        if not allowed_file(original_filename):
            return jsonify({
                "error": f"File type not allowed. Allowed: {', '.join(ALLOWED_EXTENSIONS)}"
            }), 400

        import base64
        try:
            file_data = base64.b64decode(json_data['file_base64'])
        except Exception as e:
            return jsonify({"error": "Failed to decode base64 data"}), 400

    else:
        return jsonify({"error": "Unsupported Content-Type"}), 415

    # 确保目录存在
    os.makedirs(FILE_UPLOAD_PATH, exist_ok=True)
    file_path = os.path.join(FILE_UPLOAD_PATH, original_filename)

    # 写入文件
    try:
        with open(file_path, 'wb') as f:
            f.write(file_data)
        return jsonify({
            "message": "File uploaded successfully",
            "file_path": file_path
        }), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500
